package com.exam.api.config;


import com.exam.api.common.RunnableWrapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.task.TaskDecorator;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Author bcheng
 * @Create 2024/1/13 12:11
 * @Description 线程池配置
 */
@Slf4j
@Configuration
public class ThreadPoolConfig implements TaskDecorator {
    /**
     * 项目共用线程池
     */
    public static final String APP_EXECUTOR = "appExecutor";


    @Bean(APP_EXECUTOR)
    @Primary
    public ThreadPoolTaskExecutor appExecutor(Environment environment) {
        String threadPoolId = "app-executor-";
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(Runtime.getRuntime().availableProcessors() * 2);
        executor.setMaxPoolSize(Runtime.getRuntime().availableProcessors() * 2);
        executor.setQueueCapacity(2048);
        executor.setThreadNamePrefix(threadPoolId);
        executor.setTaskDecorator(this);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//满了调用线程执行，认为重要任务
        executor.initialize();
        log.info(" <<<=== 平台线程池 名称前缀 : {} 核心线程数 : {}", threadPoolId, executor.getCorePoolSize());
        return executor;
    }


    @Override
    public Runnable decorate(Runnable runnable) {
        try {
            Optional<Map<String, String>> mdcContextMapOpt = getMDCContextMap();
            Optional<RequestAttributes> requestAttributesOpt = getCurrentRequestAttributes();
            return new RunnableWrapper(runnable, () -> {
                RequestContextHolder.resetRequestAttributes();
                MDC.clear();
                mdcContextMapOpt.ifPresent(MDC::setContextMap);
                requestAttributesOpt.ifPresent(RequestContextHolder::setRequestAttributes);
            }, () -> {
                RequestContextHolder.resetRequestAttributes();
                MDC.clear();
            });
        } catch (Exception e) {
            log.error(" <<<=== ThreadPoolTaskExecutor装饰器错误 ", e);
            return runnable;
        }
    }

    private Optional<Map<String, String>> getMDCContextMap() {
        try {
            return Optional.ofNullable(MDC.getCopyOfContextMap());
        } catch (Exception e) {
            return Optional.empty();
        }
    }

    private Optional<RequestAttributes> getCurrentRequestAttributes() {
        try {
            return Optional.of(RequestContextHolder.currentRequestAttributes());
        } catch (Exception e) {
            return Optional.empty();
        }
    }
}
